package routers

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"tapay-bot/global"
	"tapay-bot/internal/model"
	"tapay-bot/pkg/app"
	"tapay-bot/pkg/errcode"
	"tapay-bot/pkg/util/xstring"
	"time"
)

func NewRouter() *gin.Engine {
	r := gin.New()
	c := cors.Config{
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "token"},
		AllowCredentials: false,
		MaxAge:           12 * time.Hour,
	}
	c.AllowAllOrigins = true
	r.Use(cors.New(c))

	if global.ServerSetting.RunMode == "debug" {
		r.Use(gin.Logger())
	} else {
		file, _ := os.OpenFile(global.AppSetting.LogSavePath+"/gin.log", os.O_CREATE|os.O_WRONLY, 0666)
		r.Use(gin.LoggerWithConfig(gin.LoggerConfig{Output: file}))
	}
	r.Use(gin.Recovery())
	r.GET("ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "Hello, this is a WebSocket example with Gin!",
		})
	})
	return r
}

type appHandlerFunc func(*gin.Context) error

// errWrapper
//
//	@Author achilles
//	@Description: 错误包装函数
//	@param appHandler
//	@param fc
//	@date 2022-04-26 09:21:10
//	@return func(ctx *gin.Context)
func errWrapper(appHandler appHandlerFunc) func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		err := appHandler(ctx)
		if err == nil {
			return
		}
		var ok bool
		var errCode *errcode.Error
		if errCode, ok = err.(*errcode.Error); !ok {
			errLog := model.ErrorLog{}
			funcName := xstring.FunctionName(appHandler)
			errLog.CreateErrLog(global.DBEngine, app.GetUserId(ctx), fmt.Sprintf("tapay-bot errWrapper:%s", funcName), nil, err)
			if errCode == nil {
				errCode = errcode.ErrorSystemFail
			}
			errCode = errCode.WithDetails(err.Error())
		}
		response := app.NewResponse(ctx)
		response.ToErrorResponse(errCode)
	}
}
